package com.example.car

import android.app.Activity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.car.adapter.NewsListAdapter
import com.example.car.bean.NewsListBean
import com.example.car.databinding.FragmentTabNewsBinding
import com.example.car.utils.NewsApi
import com.example.car.utils.RetrofitUtils
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


class TabNewsFragment : Fragment() {
    private var title_py: String = ""
    lateinit var binding: FragmentTabNewsBinding

    val adapter: NewsListAdapter by lazy { NewsListAdapter(context as Activity) }

    companion object {
        private const val ARG_PARAM = "args"
        fun newInstance(param: String): TabNewsFragment {
            // 创建tab实例
            val fragment = TabNewsFragment()
            // 设置参数
            val args = Bundle()
            args.putString(ARG_PARAM, param)
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = FragmentTabNewsBinding.inflate(layoutInflater)

        // 在这里获取路径传参
        if (getArguments() != null) {
            // 获取参数
            title_py = getArguments()?.getString(ARG_PARAM).toString();
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding.apply {
            recyclerView.adapter = adapter
            imgError.setVisibility(View.GONE)
        }
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        getData()
    }


    fun getData() {
        val api = RetrofitUtils.getApi(NewsApi.base_url, NewsApi::class.java)
        val newsList = api.getNewsList(NewsApi.key, title_py)
        newsList?.enqueue(object : Callback<NewsListBean> {
            override fun onResponse(call: Call<NewsListBean>, response: Response<NewsListBean>) {
                val body = response.body()
                binding.loading.setVisibility(View.GONE)
                Log.d("TAG", "DATA:" + body.toString())
                if (body?.result == null) {
                    binding.imgError.setVisibility(View.VISIBLE)
                }
                body?.result?.data?.let { adapter.addData(it) }
            }

            override fun onFailure(call: Call<NewsListBean>, t: Throwable) {
                Log.d("TAG", "onFailure: " + t.toString());
            }

        })
    }

}